#!/bin/sh

# Abort on any errors
set -e

##################################
# User-editable settings (start) #
##################################

# Our personal space
WORKDIR=${HOME}/Workspace

# Where do you want all this stuff built? I'd recommend picking a local filesystem.
# ***Don't pick a directory that already exists!***
SRCDIR=${HOME}/src

# Set DISTDIR to somewhere persistent, if you plan to muck around with this
# script and run it several times!
DISTDIR=${HOME}/dist

# Update version information here.
ANT="apache-ant-1.9.1"
RJLG="rjlg_build"
INFINISPAN="infinispan-5.2.1.Final"
INFINISPAN_VER="5.2.1.Final"

##################################
# No need to edit beyond this    #
##################################

# Utility functions
function aa_grab () {
  # saves file to DISTDIR, if they don't already exist
  if [ ! -f ${DISTDIR}/`basename $1` ]; then
    echo Downloading `basename $1`
    curl -L --retry 20 --max-time 1800 --retry-delay 30 -# -f --max-redirs 4 --remote-name "$1"
  fi
}

function aa_unpack () {
  # uncompress tar, gzip, and bz2 files to SRCDIR
  if [ -f ${SRCDIR}/$1* ] && [ ! -d ${DISTDIR}/$1 ]; then
    echo Extracting $1
    tar -xvf ${SRCDIR}/$1* &>/dev/null
    echo Done.
    echo
    wait
  fi
}


echo
echo --------------------------------------------------
echo --   Run this script FIRST                      --
echo --------------------------------------------------
echo
echo - Downloads and unpacks all needed packages
echo
read -p  "        (Press return to continue)" temp;
echo;echo


# Create necessary directories.
if [ ! -d ${DISTDIR} ]; then
  mkdir -p ${DISTDIR} &>/dev/null
fi
if [ ! -d ${SRCDIR} ]; then
  mkdir -p ${SRCDIR} &>/dev/null
fi


# Download the required packages.
echo;echo
echo --- Downloading all required packages ---
echo

cd ${SRCDIR}
aa_grab http://mirror.reverse.net/pub/apache//ant/binaries/${ANT}-bin.tar.bz2
aa_grab http://wbg-devtools.hq.rjlg.com/hudson/view/Labspaces/job/rjlg-build/lastSuccessfulBuild/artifact/rjlg-build/build/artifacts/rjlg_build.zip
aa_grab http://downloads.jboss.org/infinispan/${INFINISPAN_VER}/infinispan-${INFINISPAN_VER}-src.zip
wait
echo Done.


echo
echo --- Unpacking and building ANT
echo
cd ${DISTDIR}
aa_unpack ${ANT}-bin
wait
export JAVA_HOME="/Library/Java/Home"
export ANT_HOME="${DISTDIR}/${ANT}"
export PATH="$PATH;$ANT_HOME/bin"
echo "$ANT_HOME/bin" | sudo tee -a /etc/paths
cd $ANT_HOME
ant -f fetch.xml -Ddest=system
echo Done.


echo
echo --- Brewing IVY
echo
brew install ivy
wait
export IVY_HOME="/usr/local/opt/ivy/libexec"
export PATH="$PATH;$IVY_HOME/bin"
echo "$IVY_HOME/bin" | sudo tee -a /etc/paths
cp $IVY_HOME/${IVY}.jar $ANT_HOME/lib
echo "    Done."


echo
echo --- Brewing MAVEN
echo
brew install maven
wait
export M2_HOME=/usr/local/opt/maven/libexec
export M2=$M2_HOME/bin
export PATH="$PATH;$M2"
echo "$M2" | sudo tee -a /etc/paths
echo "    Done."


echo
echo --- Brewing TOMCAT (v6.0.26)
echo
cd /usr/local/Cellar
git checkout 9e18876 /usr/local/Library/Formula/tomcat.rb
brew install tomcat
brew pin tomcat
export CATALINA_HOME="/usr/local/opt/tomcat/libexec"
export CATALINA_OPTS="-Xms512m -Xmx512m -XX:MaxNewSize=128m -XX:MaxPermSize=128m -server -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:+CMSIncrementalPacing"
export PATH="$PATH;$CATALINA_HOME/bin"
echo "$CATALINA_HOME/bin" | sudo tee -a /etc/paths
mkdir -p $CATALINA_HOME/logs && chmod 777 $CATALINA_HOME/logs
echo "    Done."


echo
echo --- Brewing and deploying SOLR
echo
brew install solr
wait
export JAVA_OPTS="-Dsolr.solr.home=/usr/local/opt/solr/libexec/example/solr"
cat > $CATALINA_HOME/conf/Catalina/localhost/solr.xml << EOF
<?xml version="1.0" encoding="utf-8"?>
<Context docBase="/usr/local/opt/solr/libexec/example/webapps/solr.war" debug="0" crossContext="true">
  <Environment name="solr/home" type="java.lang.String" value="/usr/local/opt/solr/libexec/example/solr" override="true"/>
</Context>
EOF
cp `ls /usr/local/opt/solr/libexec/example/lib/ext/*.jar` $CATALINA_HOME/webapps/solr/WEB-INF/lib
catalina.sh start
if [ ! -f $CATALINA_HOME/webapps/solr/WEB-INF/web.xml ]; then
  echo "    Waiting for solr to deploy ..."
  wait 5
fi
catalina.sh stop

echo "    Done."


echo
echo --- Unpacking, deploying, and patching INFINISPAN
echo
cd ${DISTDIR}
aa_unpack ${INFINISPAN}-src
cd ${INFINISPAN}-src/server/rest
mvn package 
cp target/infinispan.war $CATALINA_HOME/webapps/infinispan-server-rest.war
catalina.sh start
if [ ! -f $CATALINA_HOME/webapps/infinispan-server-rest/WEB-INF/web.xml ]; then
  echo "    Waiting for infininspan to deploy ..."
  wait 5
fi
catalina.sh stop

echo "    Creating infinispan-configuration.xml ..."
cat > $CATALINA_HOME/webapps/infinispan-server-rest/WEB-INF/classes/infinispan-configuration.xml << EOF
<infinispan
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="urn:infinispan:config:5.1 http://www.infinispan.org/schemas/infinispan-config-5.1.xsd"
    xmlns="urn:infinispan:config:5.1">

    <namedCache name="gadgets"/>
    <namedCache name="categories"/>
    <namedCache name="groups"/>
    <namedCache name="group"/>

</infinispan>
EOF

echo "    Patching web.xml ..."
cat << EOF | patch --no-backup-if-mismatch $CATALINA_HOME/webapps/infinispan-server-rest/WEB-INF/web.xml
--- /usr/local/opt/tomcat/libexec/webapps/infinispan-server-rest/WEB-INF/web.xml	2012-09-01 05:27:18.000000000 -0400
+++ /usr/local/opt/tomcat/libexec/webapps/infinispan-server-rest/WEB-INF/web.xml	2012-09-01 05:27:18.000000000 -0400
@@ -47,1 +47,1 @@
-         <param-value>config-samples/sample.xml</param-value>
+         <param-value>infinispan-configuration.xml</param-value>
EOF
echo "    Done."


echo
echo --- Checking out, patching, building, and installing SHINDIG
echo
cd ${DISTDIR}
mkdir shindig && cd shindig
svn checkout http://svn.apache.org/repos/asf/shindig/trunk/ .

# echo "    Patching shindig.properties ..."
# cat << EOF | patch --no-backup-if-mismatch $DISTDIR/shindig/java/common/conf/shindig.properties
# --- $DISTDIR/shindig/java/common/conf/shindig.properties	2013-05-10 10:32:00.000000000 -0400
# +++ $DISTDIR/shindig/java/common/conf/shindig.properties	2013-05-10 10:32:00.000000000 -0400
# @@ -32,2 +32,2 @@
# -shindig.signing.key-name=
# -shindig.signing.key-file=
# +shindig.signing.key-name=oauthkey
# +shindig.signing.key-file=res://oauthkey.pem
# EOF

echo "    Building Shindig (this could take a while) ..."
mvn clean install -DskipTests > /dev/null 2>&1

echo "    Installing Shindig, starting Tomcat ..."
# If Tomcat is already running, undeploy ROOT instead of manually deleting ROOT...
# curl -Lfsu tomcat:tomcat "http://localhost/manager/undeploy?path=/"
rm -rf $CATALINA_HOME/webapps/ROOT.war $CATALINA_HOME/webapps/ROOT
cp `ls java/server/target/shindig-server-*-SNAPSHOT.war` $CATALINA_HOME/webapps/ROOT.war
catalina.sh start
if [ ! -f $CATALINA_HOME/webapps/ROOT/WEB-INF/web.xml ]; then
  echo "    Waiting for Shindig to deploy ..."
  wait 5
fi
echo "    Done."

# echo "    Generating oauthkey.pem ..."
# openssl req -newkey rsa:1024 -days 365 -nodes -x509 -keyout tempkey.pem -out tempkey.pem -subj /CN=oauthkey > /dev/null 2>&1
# openssl pkcs8 -in tempkey.pem -out oauthkey.pem -topk8 -nocrypt -outform PEM > /dev/null 2>&1
# mv oauthkey.pem $CATALINA_HOME/webapps/ROOT/WEB-INF/classes/oauthkey.pem
# rm tempkey.pem
# 
# echo "    Patching container.js ..."
# RPCTOKEN="$(dd if=/dev/random bs=32 count=1 | openssl base64)"
# 
# cat << EOF | patch --no-backup-if-mismatch $CATALINA_HOME/webapps/ROOT/WEB-INF/classes/containers/default/container.js
# --- $CATALINA_HOME/webapps/ROOT/WEB-INF/classes/containers/default/container.js	2013-07-13 00:32:54.000000000 -0400
# +++ $CATALINA_HOME/webapps/ROOT/WEB-INF/classes/containers/default/container.js	2013-07-13 00:32:54.000000000 -0400
# @@ -80,1 +80,1 @@
# -"gadgets.securityTokenType" : "insecure",
# +//"gadgets.securityTokenType" : "insecure",
# @@ -87,2 +87,2 @@
# -//"gadgets.securityTokenType" : "secure",
# -//"gadgets.securityTokenKey" : "default-insecure-embedded-key",
# +"gadgets.securityTokenType" : "secure",
# +"gadgets.securityTokenKey" : "$RPCTOKEN",
# EOF
# echo "    Done."
# 
# echo "    Reloading Shindig ..."
# curl -Lfsu tomcat:tomcat "http://localhost/manager/reload?path=/"
# echo "    Done."

echo
echo --- Unpacking, building and installing SWIFT
echo
cd ${SRCDIR}
mkdir -p ${RJLG} && cd ${RJLG}
aa_unpack ${RJLG}
echo "    Building & Installing..."
ant install.swift > /dev/null 2>&1
echo "    Done!"


exit 0;